# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: inkyu

import json
import re

from datetime import datetime
from pymongo import MongoClient


class JsonParser(object):
  def __init__(self, db_name, *, on_push, dry_run=False):
    self._storage = {}
    self._db_name = db_name
    self._db = MongoClient(
        'mongodb://inkyu_legacy:xArT3T#dXtGfSBDV@13.251.33.84:42006/coin_20181121'
    ).legacy_20181201[db_name]
    self._pnl = MongoClient(
        'mongodb://inkyu_legacy:xArT3T#dXtGfSBDV@13.251.33.84:42006/coin_20181121'
    ).pnl_20181201[db_name]
    self._timestamp = None
    self._state = 0
    self._krw = None
    self._usdt = None
    self._on_push = on_push
    self._dry_run = dry_run

  def _push_legacy(self, payload):
    self._on_push(self._db_name, 'chart', payload)
    if not self._dry_run:
      self._db.insert_one(payload)

  def _push_pnl(self, payload):
    self._on_push(self._db_name, 'pnl', payload)
    if not self._dry_run:
      self._pnl.insert_one(payload)

  def handle(self, line):
    if line.startswith('BALANCE'):
      json_value = json.loads(line[8:])
      self._timestamp = datetime.strptime(json_value['timestamp'], '%Y-%m-%d %H:%M:%S.%f')
      self._push_legacy({
          'timestamp': self._timestamp,
          'tag': json_value['currency0'],
          'value': json_value['quote0'] + json_value['pos0']
      })
      self._push_legacy({
          'timestamp': self._timestamp,
          'tag': json_value['currency1'],
          'value': json_value['quote1'] + json_value['pos1']
      })
      currency0 = json_value['currency0'].lower()
      currency1 = json_value['currency1'].lower()
      self._storage[currency0] = json_value['quote0']
      self._storage[currency1] = json_value['quote1']
      self._storage[currency0 + '_pos'] = json_value['pos0']
      self._storage[currency1 + '_pos'] = json_value['pos1']
      self._storage[currency0 + '_bal'] = json_value['bal0']
      self._storage[currency1 + '_bal'] = json_value['bal1']
      self._storage[currency0 + '_reserve'] = json_value['reserve0']
      self._storage[currency1 + '_reserve'] = json_value['reserve1']

    elif line.startswith('* 2018'):
      self._timestamp = datetime.strptime(line[2:-1], '%Y-%m-%d %H:%M:%S.%f')
    elif line.startswith('MasterPrices'):
      splitted = re.split('[ ()=]+', line)
      gmean_price = float(splitted[2][:-1])
      ema_price = float(splitted[4][:-1])
      self._push_legacy({'timestamp': self._timestamp, 'tag': 'GMEAN_PRICE', 'value': gmean_price})
      self._push_legacy({'timestamp': self._timestamp, 'tag': 'EMA_PRICE', 'value': ema_price})
      self._storage['ema_price'] = ema_price
      self._storage['gmean_price'] = gmean_price
      self._storage['timestamp'] = self._timestamp
      self._push_pnl(self._storage)
      self._storage = {}
